package cn.net.withub.dataCollector.common.base;

import cn.net.withub.dataCollector.common.editor.*;
import cn.net.withub.dataCollector.common.model.CourtInfo;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component(value="baseControl")
public class BaseController implements ServletContextAware {

	public static final String LOGIN_LOGINSESSION_KEY = "courtInfo";
	
	protected Integer statusCode = 404;//状态码
	protected String message = "系统繁忙,请稍后再试！";// 信息提示用
	protected String navTabId = "";//列表ID
	protected String callbackType = "closeCurrent";//回调方式
	
	private Logger log= Logger.getLogger(this.getClass());
	
	
	protected HttpSession session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected ServletContext servletContext;
	protected String errMsg = "";
	public static CourtInfo user;
	static{
		user = new CourtInfo();
		user.setUserId("0823");
		user.setUserName("黄新木");
		user.setFyDm("M00");
		user.setFyJbm("2950");
		user.setDepartId("069");
		user.setDepartName("立案庭");
		user.setFirstDepartId("069");
		user.setFirstDepartName("立案庭");
		user.setFyjb("2");
		user.setFyMc("重庆高级人民法院");
		user.setLoginName("0823");
		user.setPassword("9");
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(int.class, new IntegerEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(Date.class, new DateEditor());
		binder.registerCustomEditor(Boolean.class, new BooleanEditor());
	}
	
	
	/**
	 * 对servletAPI进行赋值
	 * @author liangtao
	 * @param req
	 * @param rep
	 * @param session
	 */
	@ModelAttribute
	public void initServletAPI(HttpServletRequest req, HttpServletResponse rep, HttpSession session){
		this.request=req;
		this.response = rep;
		this.session=session;
	}

	public void pushCourtInfo(CourtInfo courtInfo)throws Exception{
		getSession().setAttribute(LOGIN_LOGINSESSION_KEY, courtInfo);
	}

	public String getBgqDate(String startDate,String endDate)throws Exception{
		return startDate.replace("-","")+","+endDate.replace("-","");
	}

	public CourtInfo getCourtInfo(){
		CourtInfo courtInfo = (CourtInfo)getSession().getAttribute(LOGIN_LOGINSESSION_KEY);
		List lst  = courtInfo.getRoleList();
		if(lst.size() == 0)lst.add("analyis_by");
		return  courtInfo;
	}
	
	/**
	 * 摧毁SESSION
	 * 
	 */
	public void removeSessionUser() {
		getSession().removeAttribute(LOGIN_LOGINSESSION_KEY);
	}
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setSession(HttpSession session) {
		this.session = session;

	}

	public HttpSession getSession() {
		return session;
	}

	public String objToString(Object obj){
		return obj==null?null:obj.toString().trim();
	}
	
	public Integer objToInteger(Object obj){
		return obj==null?null: Integer.parseInt(obj.toString().trim());
	}
	
	public String getRequestValue(String name){
		return getRequest().getParameter(name)==null|| getRequest().getParameter(name).trim().equals("")?"": getRequest().getParameter(name).trim();
	}
	
	public String[] getRequestValues(String name){
		return getRequest().getParameterValues(name)==null|| getRequest().getParameterValues(name).equals("")?new String[0]: getRequest().getParameterValues(name);
	}
	
	protected String getMessage(Integer type, Integer status) {
		String[] ty  = new String[]{"添加","更新","删除","操作"};
		String[] sta = new String[]{"失败！","成功！"};
		return ty[type]+sta[status];
	}
	
	protected Map getMessageMap(final Integer statusCode, final String message){
		Map map = new HashMap(){
			{
				put("statusCode",statusCode);
				put("message",message);
			}
		};
		return map;
	}

	protected Map getMessageMap(){
		Map map = new HashMap(){
			{
				put("statusCode",statusCode);
				put("message",message);
			}
		};
		return map;
	}
	
	protected void initBadStatus(Integer type){
		String[] ty  = new String[]{"添加","更新","删除","操作"};
		this.statusCode = 404;
		this.message = ty[type]+"失败!";
	}

	protected void initSuccessStatus(Integer type){
		String[] ty  = new String[]{"添加","更新","删除","操作"};
		this.statusCode = 200;
		this.message = ty[type]+"成功!";
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	//获取用户云中心角色权限
	public String getRole() throws Exception{
		CourtInfo courtInfo = (CourtInfo)getSession().getAttribute(LOGIN_LOGINSESSION_KEY);
		List<String> roleList  = null;
		if(courtInfo.getRoleList() != null){
			roleList  = courtInfo.getRoleList();
		}
		boolean role_by = false;
		boolean role_xq = false;
		boolean role_qs = false;
		if(roleList !=null && roleList.size()>0){
			for(String role : roleList){
				if(role.equals("analyis_by")){
					role_by = true;
				}else if(role.equals("analyis_xq")){
					role_xq = true;
				}else if(role.equals("analyis_qs")){
					role_qs = true;
				}
			}
		}
		String role = (role_qs==true?"analyis_qs":(role_xq==true?"analyis_xq":(role_by==true?"analyis_by":"")));
		log.info("当前用户["+courtInfo.getUserName()+"]角色["+role+"]");

		return role;
	}

	public void responseJsonStringData(String json){
		try {
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache, must-revalidate");
			response.setHeader("Pragma", "no-cache");
			response.getWriter().write(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 返回json对象
	 * @param statusCode 状态
	 * @param message 信息
	 * @param navTabId 列表id
	 * @param rel
	 * @param callbackType 回调方法类型 closeCurrent:关闭弹窗
	 * @param forwardUrl 跳转路径
	 * @param confirmMsg
	 * @throws Exception
	 */
	public void responseJsonReturnData(String statusCode,String message,String navTabId,String rel,String callbackType,String forwardUrl,String confirmMsg)throws Exception{
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		JSONObject retObj = new JSONObject();
		retObj.put("statusCode", statusCode);
		retObj.put("message", message);
		retObj.put("navTabId", navTabId);
		retObj.put("rel", rel);
		retObj.put("callbackType", callbackType);
		retObj.put("forwardUrl", forwardUrl);
		retObj.put("confirmMsg", confirmMsg);
		log.info(retObj.toString());
		response.getWriter().write(retObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
}
